package com.example.handler;

import com.example.annotations.Controller;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

public class RootHandler implements HttpHandler {

    private static final Logger log = Logger.getLogger(RootHandler.class.getCanonicalName());

    private Object object;

    private Method method;

    public RootHandler() {

    }

    public RootHandler(Method method,Object object) {
        this.method = method;
        this.object = object;
    }

    @Override
    public void handle(HttpExchange httpExchange) {
        Object result = null;
        try {
            Object[] params = getQueryString(httpExchange);
            if(method.getParameters().length > params.length){
                result= "wrong number of arguments";
            }else {
                result = method.invoke(object,params);
            }
            if(result == null){
                return;
            }
            byte[] totalByte = result.toString().getBytes(StandardCharsets.UTF_8);
            httpExchange.getResponseHeaders().add("content-type","text/html;charset=utf-8");
            httpExchange.sendResponseHeaders(200,totalByte.length);
            OutputStream os = httpExchange.getResponseBody();
            InputStream is = new ByteArrayInputStream(totalByte);
            byte[] buf = new byte[1024];
            int len = -1;
            while((len=is.read(buf))>-1){
                os.write(buf,0,len);
                os.flush();
            }
            os.close();
            is.close();
            System.out.println("离开RootHandler");
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.log(Level.SEVERE,"反射调用出错",e);
            throw new RuntimeException(e);
        }catch (Exception e){
            log.log(Level.SEVERE,"处理handler出错",e);
        }

    }

    private Object[] getQueryString(HttpExchange httpExchange){
        Parameter[] parameters = method.getParameters();
        String[] values;
        String queryString = httpExchange.getRequestURI().getQuery();
        if(queryString == null){
            return new Object[]{httpExchange};
        }
        Object[] params = new Object[parameters.length];
        if(queryString.contains("&")){
            String[] keyValueArr = queryString.split("&");
            values = new String[keyValueArr.length];
            for(int i = 0;i < keyValueArr.length;i++){
                String value = keyValueArr[i].split("=")[1];
                values[i] = value;
            }
        }else{
            values = new String[1];
            String value = queryString.split("=")[1];
            values[0] = value;
        }
        for( int i = 0;i< parameters.length;i++){
            if(i == 0){
                params[i]=httpExchange;
                continue;
            }
            params[i]=values[i-1];
        }
        return params;
    }
}
